package gui;

import classes.Lotacao;
import java.awt.event.KeyEvent;
import org.apache.commons.lang3.StringUtils;
import erro.ConexaoException;
import erro.ConsultaException;
import fachada.Fachada;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Roberta
 */
public class LotacaoCadastrar extends javax.swing.JFrame {

    /** Creates new form LotacaoCadastrar */
    public LotacaoCadastrar() {
        initComponents();
        this.setLocationRelativeTo(null);
        carregarTabela();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textSigla = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        textNome = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        btExcluir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbLotacao = new javax.swing.JTable();
        btAlterar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        btIncluir = new javax.swing.JButton();
        btLimpar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Lotação");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Sigla:");

        jLabel4.setText("Nome:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textSigla, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textNome, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(55, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textSigla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Lotações:"));

        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/excluir.png"))); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        tbLotacao.setAutoCreateRowSorter(true);
        tbLotacao.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Sigla", "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbLotacao.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbLotacaoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbLotacao);
        tbLotacao.getColumnModel().getColumn(0).setPreferredWidth(70);
        tbLotacao.getColumnModel().getColumn(0).setMaxWidth(100);

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/editar.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                    .addComponent(btAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btExcluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btAlterar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))
                .addContainerGap())
        );

        btIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/adicionar.png"))); // NOI18N
        btIncluir.setText("Incluir");
        btIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIncluirActionPerformed(evt);
            }
        });
        btIncluir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btIncluirKeyPressed(evt);
            }
        });

        btLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/limpar.png"))); // NOI18N
        btLimpar.setText("Limpar");
        btLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimparActionPerformed(evt);
            }
        });
        btLimpar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btLimparKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btIncluir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btLimpar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(btIncluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btLimpar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btIncluirActionPerformed
        try {
            Fachada f = new Fachada();
            Lotacao l = new Lotacao();
            String nome = textNome.getText().toLowerCase().trim();
            StringTokenizer stE = new StringTokenizer(nome, " ");
            String convertido = "";
            while (stE.hasMoreTokens()) {
                String fMaiuscula = StringUtils.capitalize(stE.nextToken().trim() + " ");
                convertido += fMaiuscula;
            }
            l.setSigla(textSigla.getText().toUpperCase().trim());
            l.setNome(convertido);
            f.inserir(l);
            carregarTabela();
        } catch (ConexaoException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
        } catch (ConsultaException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível inserir a nova Lotação!\n" + e);
        }
    }//GEN-LAST:event_btIncluirActionPerformed

    private void btLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparActionPerformed
        textNome.setText("");
        textSigla.setText("");
    }//GEN-LAST:event_btLimparActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir?", "Alerta!", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            int size = tbLotacao.getSelectedRowCount();
            if (size > 1) {
                JOptionPane.showMessageDialog(null, "Selecione apenas uma lotação por vez!");
                tbLotacao.setSelectionMode(1);
            } else {
                Lotacao l = new Lotacao();
                Fachada f = new Fachada();
                ArrayList<Lotacao> lista;
                try {
                    lista = f.listar(l);
                    DefaultTableModel modelo = (DefaultTableModel) tbLotacao.getModel();
                    int r = tbLotacao.getSelectedRow();
                    String servAtual = modelo.getValueAt(r, 0).toString();
                    for (Lotacao lo : lista) {
                        if (lo.getSigla().equals(servAtual)) {
                            f.deletar(lo);
                            carregarTabela();
                        }
                    }
                } catch (ConexaoException e) {
                    JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
                } catch (ConsultaException e) {
                    JOptionPane.showMessageDialog(null, "Não foi possível excluir a Lotação!. Talvez ela esteja em uso.\n" + e);
                }
            }
        } else {
            this.repaint();
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    private void btIncluirKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btIncluirKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btIncluirActionPerformed(null);
        }
    }//GEN-LAST:event_btIncluirKeyPressed

    private void btLimparKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btLimparKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btLimparActionPerformed(null);
        }
    }//GEN-LAST:event_btLimparKeyPressed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        Lotacao l = new Lotacao();
        Fachada f = new Fachada();
        ArrayList<Lotacao> lista;
        try {
            lista = f.listar(l);
            DefaultTableModel modelo = (DefaultTableModel) tbLotacao.getModel();
            int r = tbLotacao.getSelectedRow();
            String atual = modelo.getValueAt(r, 1).toString();
            for (Lotacao lo : lista) {
                if (lo.getNome().equals(atual)) {
                    String nome = textNome.getText().toLowerCase().trim();
                    StringTokenizer stE = new StringTokenizer(nome, " ");
                    String convertido = "";
                    while (stE.hasMoreTokens()) {
                        String fMaiuscula = StringUtils.capitalize(stE.nextToken().trim() + " ");
                        convertido += fMaiuscula;
                    }
                    l.setNome(convertido);
                    l.setSigla(textSigla.getText().toUpperCase().trim());
                    l.setLotacao_id(lo.getLotacao_id());
                    f.alterarLot(l);
                    carregarTabela();
                    textNome.setText("");
                    textSigla.setText("");
                }
            }
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível alterar a Lotação.\n" + ex);
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void tbLotacaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLotacaoMouseClicked
        if (evt.getClickCount() == 2 || evt.getButton() == MouseEvent.BUTTON1) {//se o clique for duplo
            DefaultTableModel modelo = (DefaultTableModel) tbLotacao.getModel();
            int r = tbLotacao.getSelectedRow();
            String atual = modelo.getValueAt(r, 1).toString();
            String sigla = modelo.getValueAt(r, 0).toString();
            textNome.setText(atual);
            textSigla.setText(sigla);
        }
    }//GEN-LAST:event_tbLotacaoMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LotacaoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LotacaoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LotacaoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LotacaoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new LotacaoCadastrar().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btIncluir;
    private javax.swing.JButton btLimpar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbLotacao;
    private javax.swing.JTextField textNome;
    private javax.swing.JTextField textSigla;
    // End of variables declaration//GEN-END:variables

    public final void carregarTabela() {
        Fachada f = new Fachada();
        Lotacao l = new Lotacao();
        DefaultTableModel modelo = (DefaultTableModel) tbLotacao.getModel();
        modelo.setNumRows(0);
        ArrayList<Lotacao> lista = new ArrayList<Lotacao>();
        try {
            lista = f.listar(l);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tabela.\n" + ex);
        }
        for (int i = 0; i < lista.size(); i++) {
            modelo.addRow(new Object[]{lista.get(i).getSigla(), lista.get(i).getNome()});
        }
        tbLotacao.setModel(modelo);
    }
}
